#!/usr/bin/env python
# encoding: utf-8
"""
#-------------------------------------------------------------------#
#                   CONFIDENTIAL --- CUSTOM STUDIOS                 #     
#-------------------------------------------------------------------#
#                                                                   #
#                   @Project Name : Globallawonline                #
#                                                                   #
#                   @File Name    : wordtopdf.py                      #
#                                                                   #
#                   @Programmer   : 李建                            #
#                                                                   #  
#                   @Start Date   : 2021/5/12 11:26                 #
#                                                                   #
#                   @Last Update  : 2021/5/12 11:26                 #
#                                                                   #
#-------------------------------------------------------------------#
# Classes: 用于将word文件转为pdf文件                                                         #
#                                                                   #
#-------------------------------------------------------------------#
"""
import os
import shutil
import sys
import time

from win32com.client import Dispatch, DispatchEx
from win32com.client import constants
from win32com.client import gencache
import re


def getfilenames(filepath='', file_ext='all', filelist_out=None):
    for fpath, dirs, fs in os.walk(filepath):
        for f in fs:
            fi_d = os.path.join(fpath, f)
            if file_ext == '.doc':
                if os.path.splitext(fi_d)[1] in ['.doc', '.docx']:
                    filelist_out.append(re.sub(r'\\', '/', fi_d))
            else:
                if file_ext == 'all':
                    filelist_out.append(fi_d)
                elif os.path.splitext(fi_d)[1] == file_ext:
                    filelist_out.append(fi_d)
                else:
                    pass
        filelist_out.sort()
    return filelist_out


# Word to PDF
def wordtopdf(filelist, targetpath):
    valueList = []
    try:
        gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
        # 开始转换
        w = Dispatch("Word.Application")
        for fullfilename in filelist:
            (filepath, filename) = os.path.split(fullfilename)  # 分割文件路径和文件名
            softfilename = os.path.splitext(filename)  # 分割文件名和扩展名
            os.chdir(filepath)
            doc = os.path.abspath(filename)
            os.chdir(targetpath)
            pdfname = softfilename[0] + ".pdf"
            output = os.path.abspath(pdfname)
            pdf_name = output

            try:
                doc = w.Documents.Open(doc, ReadOnly=1)
                doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF,
                                        Item=constants.wdExportDocumentWithMarkup,
                                        CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
            except Exception as e:
                print(e)
            if os.path.isfile(pdf_name):
                valueList.append(pdf_name)
            else:
                print('转换失败！')
                erro_dir = os.path.join(filepath, '\erro')
                if not os.path.exists(erro_dir):
                    os.makedirs(erro_dir)
                try:
                    shutil.copyfile(fullfilename, os.path.join(erro_dir, filename))
                except Exception as e:
                    with open("copyerro.txt", "a", encoding='utf-8') as f:
                        f.write(fullfilename + '\n')
                    print("文件复制出错:%s(%s)" % (fullfilename, str(e)))
                return False
        w.Quit(constants.wdDoNotSaveChanges)
        return valueList
    except TypeError as e:
        print('出错了！')
        print(e)
        return False


if __name__ == '__main__':
    # 待处理word文件路径
    file_source_root = input("请输入待转化word文件路径: ")
    try:
        sourcepath = os.path.join(file_source_root)
    except:
        print("input erro")
        time.sleep(5)
        sys.exit(0)
    # 输入pdf文件输出路径
    file_target_root = input("请输入pdf文件输出路径: ")
    try:
        targetpath = os.path.join(file_target_root)
    except:
        print("input erro")
        time.sleep(5)
        sys.exit(0)
    if not os.path.exists(targetpath):
        os.makedirs(targetpath)
    filelist = getfilenames(sourcepath, '.doc')  # 获取Word文档路径
    valueList = wordtopdf(filelist, targetpath)  # 实现将Word文档批量转换为PDF
    if valueList:
        print("转换成功")
    else:
        print("没有要转换的Word文档或者转换失败！请检查！")